package com.example.itcompanyinterview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.example.itcompanyinterview.container.QuestionRateAdapter;
import com.example.itcompanyinterview.object.*;
import com.example.itcompanyinterview.tools.AboutDialog;
import com.example.itcompanyinterview.tools.CommonJsonParser;
import com.example.itcompanyinterview.tools.CommonUrlRequest;
import com.example.itcompanyinterview.tools.LoadingDialogHelper;
import com.example.itcompanyinterview.tools.MenuHelper;
import com.example.itcompanyinterview.tools.TitleBarGenerator;

public class QuestionListActivity extends Activity {

	private Role parentRole;
	private Handler messageHandler;
	private static String QUESTION_CONTROLER = "Question";
	private static String GET_QUESTION_LIST_ACTION = "GetQuestionsInRole";
	private static int GET_QUESTION_LIST = 0x03;
	private static int LOAD_QUESTION_NUM_PER_ACTION = 10;
	private int already_load_question_num = 0;
	private List<InterviewQuestion> listQuestions;
	private QuestionRateAdapter adapter;
	
	private LoadingDialogHelper loadingHelper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_question_list);
		this.getCompanyAndRole();
		this.initActivityTitleBar();
		this.initViewsAndMember();
		this.setQuestionListClickListener();
		this.initMessageHandler();
		this.getQuestionListFromUrl();
	}

	private void initActivityTitleBar() {
		TitleBarGenerator titleBar = new TitleBarGenerator(this);
		titleBar.setActionButtonView(View.GONE);
		titleBar.setTitleText(this.parentRole.getName());
		titleBar.showTitleBar();
	}

	private void initViewsAndMember(){
		this.loadingHelper = new LoadingDialogHelper(this);
		this.listQuestions = new ArrayList<InterviewQuestion>();
		this.initListViewAdapterAndLoadMore();
	}
	
	
	private void initListViewAdapterAndLoadMore() {
		ListView questionListView = (ListView)this.findViewById(R.id.questionList);
		questionListView.addFooterView(this.getLayoutInflater().inflate(R.layout.question_list_addmore, null));
		this.adapter = new QuestionRateAdapter(this, this.listQuestions ,questionListView);
		questionListView.setAdapter(this.adapter);
		
		final Button addMoreButton = (Button)this.findViewById(R.id.load_more_question);
		addMoreButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				addMoreButton.setVisibility(View.GONE);
				getQuestionListFromUrl();
				addMoreButton.setVisibility(View.VISIBLE);
			}
			
		});
	}
	
	private void getCompanyAndRole() {
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		this.parentRole = (Role)bundle.getSerializable("role");
	}
	
	public void setQuestionListClickListener() {
		ListView questionListView = (ListView) this
				.findViewById(R.id.questionList);
		questionListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View arg1, int pos,
					long id) {
				arg1.setSelected(true);
				InterviewQuestion question = (InterviewQuestion) parent
						.getItemAtPosition(pos);
				Bundle bundle = new Bundle();
				bundle.putSerializable("question", question);
				Intent intent = new Intent(QuestionListActivity.this,
						QuestionDetailActivity.class);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
	}
	
	private void initMessageHandler() {
    	this.messageHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if(msg.what == GET_QUESTION_LIST) {
					loadingHelper.closeLoadingDialog();
					String questionJsonString = (String)msg.obj;
			    	if(questionJsonString == null) {
			    		Toast.makeText(QuestionListActivity.this, "获取题目列表失败，请检测网络",
			    				Toast.LENGTH_SHORT).show();
			    		return;
			    	}
			    	initQuestionList(questionJsonString);
				}
				super.handleMessage(msg);
			}
    		
    	};
    }
	
	private void getQuestionListFromUrl() {
		new Thread(new Runnable() {
			public void run() {
				List<Pair<String, String>> paramList = new ArrayList<Pair<String, String>>();
				CommonUrlRequest.setParam(paramList, "roleid", String.valueOf(parentRole.getId()));
				CommonUrlRequest.setParam(paramList, "questionlength", String.valueOf(LOAD_QUESTION_NUM_PER_ACTION));
				CommonUrlRequest.setParam(paramList, "questionoffset", String.valueOf(already_load_question_num));
				String roleQuestionString = CommonUrlRequest
						.getControllerAndAction(QuestionListActivity.QUESTION_CONTROLER,
								QuestionListActivity.GET_QUESTION_LIST_ACTION, paramList);
				Message m = messageHandler.obtainMessage();
				m.obj = roleQuestionString;
				m.what = QuestionListActivity.GET_QUESTION_LIST;
				messageHandler.sendMessage(m);
			}
		}).start();
		this.loadingHelper.showLoadingDialog();
	}
	
	public void initQuestionList(String jsonQuestionString) {
		try {
			JSONObject jsonQuestionRet = CommonJsonParser
					.parseJsonObject(jsonQuestionString);
			if (jsonQuestionRet.getInt("err") != 0) {
				Toast.makeText(QuestionListActivity.this,
						"获取失败:" + jsonQuestionRet.getString("msg"),
						Toast.LENGTH_LONG).show();
				return;
			}

			JSONArray jsonQuestionList = CommonJsonParser
					.parseJsonArray(jsonQuestionRet.getString("value"));
			int questionNum = jsonQuestionList.length();
			
			for (int i = 0; i < questionNum; i++) {
				JSONObject jsonQuestionObj = jsonQuestionList.getJSONObject(i);
				InterviewQuestion interviewQuestion = new InterviewQuestion();
				interviewQuestion.setId(jsonQuestionObj.getInt("id"));
				interviewQuestion.setTitle(jsonQuestionObj.getString("title"));
				interviewQuestion.setRate(jsonQuestionObj.getInt("rate"));
				interviewQuestion.setCompanyString(jsonQuestionObj.getString("company"));
				interviewQuestion.setRoleId(this.parentRole.getId());
				
				listQuestions.add(interviewQuestion);
			}
			
			this.adapter.notifyDataSetChanged();
			
			this.already_load_question_num = this.already_load_question_num + questionNum;
			if(QuestionListActivity.LOAD_QUESTION_NUM_PER_ACTION > questionNum) {
				this.setMoreButtonUnClickable();
			}
		} catch (JSONException e) {
			Toast.makeText(QuestionListActivity.this,
					"发生了异常:" + e.getMessage(), Toast.LENGTH_LONG).show();
			Log.e("InitCompanyList", e.getMessage());
		}
	}
	
	private void setMoreButtonUnClickable() {
		Button loadMoreButton = (Button)this.findViewById(R.id.load_more_question);
		loadMoreButton.setText("所有题目已加载完成");
		loadMoreButton.setTextColor(Color.GRAY);
		loadMoreButton.setClickable(false);
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	MenuHelper menuHelper = new MenuHelper(this, item);
    	menuHelper.processMenu();
    	return super.onOptionsItemSelected(item);
    }
	
	

}
